<?php

namespace Aitels\Foundation\Schedule;

use Illuminate\Console\Scheduling\Schedule;
use  Aitels\Foundation\Annotation\ApplicationAnnotationsContainer;
use  Aitels\Foundation\Annotation\ScheduleAnnotation;
use  Aitels\Foundation\Code\ClassAnalyser;
use Illuminate\Support\Facades\Log;

class AnnotationScheduleRegister
{
    public function register(Schedule $schedule)
    {

        $scheduleAnnotations = ApplicationAnnotationsContainer::getApplicationAnnotations(ScheduleAnnotation::NAME);

        foreach ($scheduleAnnotations as $classPath => $methodsAnnotations) {
            foreach ($methodsAnnotations as $methodName => $methodAnnotations) {

                foreach ($methodAnnotations as $methodAnnotation) {
                    $callbackEvent = $schedule->call(
                    //我们简单的并创建一个实例化该类并执行该方法的闭包
                        function () use ($classPath, $methodName) {
                            $class = ClassAnalyser::getClassByPath($classPath);
                            $instance = new $class;
                            try {
                                $instance->{$methodName}();
                            } catch (\Throwable $e) {
                                $reflection = new \ReflectionClass($e);
                                if ($reflection->hasMethod('report')) {
                                    $e->report();
                                } else {
                                    Log::error(sprintf('定时任务[%s@%s]抛出异常', $class, $methodName), ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);

                                }
                            }
                        }
                    );


                    foreach ($methodAnnotation as $key => $scheduleConstraint) {
                        if (is_array($scheduleConstraint)) {
                            if (count($scheduleConstraint) === 1)
                                $callbackEvent->{$key}($scheduleConstraint[0]);
                            if (count($scheduleConstraint) === 2)
                                $callbackEvent->{$key}($scheduleConstraint[0], $scheduleConstraint[1]);
                            if (count($scheduleConstraint) === 3)
                                $callbackEvent->{$key}($scheduleConstraint[0], $scheduleConstraint[1], $scheduleConstraint[2]);
                        } else {

                            $callbackEvent->{$scheduleConstraint}();
                        }
                    }
                }
            }
        }


    }


}